/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package principal;

/**
 *
 * @author Fabricio
 */
public class Arbol {

     private Nodo Raiz;

     public Arbol(){ Raiz=null;}

     // insertar(Raiz, Raiz, x)


      public boolean arbolVacio(){return Raiz == null;}


      public void insertar(Nodo ant, Nodo p, Nodo x){

         if (p != null){
             if (Integer.parseInt(x.getDato().toString()) >                 Integer.parseInt(p.getDato().toString())) {
                   insertar(p, p.getPd(), x);
                }else{
                   insertar(p, p.getPi(), x);
                }
            }else{
               if (arbolVacio()){
                     Raiz = x;
               }else{
                  if (Integer.parseInt(x.getDato().toString()) >  Integer.parseInt(ant.getDato().toString())) {
                    ant.setPd(x);
                  }else {
                     ant.setPi(x);
                  }
               }
            }
}

public void imprimir(Nodo p){

if(p != null){
       imprimir(p.getPi());
       System.out.print(p.getDato()+"; ");
       imprimir(p.getPd());
}
}

public Nodo getRaiz() {
   return Raiz;
}
public void setRaiz(Nodo raiz) {
    Raiz = raiz;
}


public void eliminar(Nodo ant, Nodo p){
   if(esNodoHoja(p)){
         eliminarNodoHoja(ant, p);
   }else{
        if (esNodoCon2SubArboles(p)){
//              eliminarNodoCon2SubArboles(ant, p);
        }else{
           eliminarNodoCon1SubArnol(ant, p);
        }
    }
}

public void eliminarNodoHoja(Nodo ant, Nodo p){
if (Raiz != p){
   if(ant.getPd() == p){
          ant.setPd(null);
   }else{
         ant.setPi(null);
   }
}else{
   Raiz = null;
}
}



public void eliminarNodoCon1SubArnol(Nodo ant, Nodo p){
if (Raiz == p){
     if(p.getPd() != null){
         Raiz = Raiz.getPd();
     }else{
         Raiz = Raiz.getPi();
     }
}else{
     if ( ant.getPd() == p){
           if(p.getPd() != null){
                ant.setPd(p.getPd());
           }else{
               ant.setPd(p.getPi());
           }
    }else{
        if(p.getPd() != null){
            ant.setPi(p.getPd());
        }else{
           ant.setPi(p.getPi());
    }
}
}
}


public boolean esNodoHoja(Nodo p){return (p.getPi() == null && p.getPd() == null);}

public boolean esNodoCon2SubArboles(Nodo p){return (p.getPi() != null && p.getPd() != null);}

}